const jwt = require('jsonwebtoken');
const Admin = require('../models/Admin');
require('dotenv').config();

const JWT_SECRET = process.env.JWT_SECRET || 'hun_action_jwt_secret_key_2024';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7200'; // 2小时

/**
 * 生成JWT Token
 * @param {Object} payload - 载荷数据
 * @returns {string} - JWT Token
 */
function generateToken(payload) {
  return jwt.sign(payload, JWT_SECRET, { 
    expiresIn: parseInt(JWT_EXPIRES_IN) 
  });
}

/**
 * 验证JWT Token
 * @param {string} token - JWT Token
 * @returns {Object} - 解码后的载荷
 */
function verifyToken(token) {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch (error) {
    throw new Error('Invalid token');
  }
}

/**
 * JWT认证中间件
 */
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

  if (!token) {
    return res.status(401).json({
      code: 401,
      message: '未提供认证令牌',
      timestamp: Date.now()
    });
  }

  try {
    const decoded = verifyToken(token);
    req.admin = decoded;
    next();
  } catch (error) {
    return res.status(401).json({
      code: 401,
      message: '认证令牌无效或已过期',
      timestamp: Date.now()
    });
  }
}

/**
 * 角色权限检查中间件
 * @param {string|Array} requiredRoles - 需要的角色
 */
function requireRole(requiredRoles) {
  if (typeof requiredRoles === 'string') {
    requiredRoles = [requiredRoles];
  }

  return async (req, res, next) => {
    try {
      if (!req.admin) {
        return res.status(401).json({
          code: 401,
          message: '未认证',
          timestamp: Date.now()
        });
      }

      // 获取管理员完整信息
      const admin = await Admin.findById(req.admin.id);
      if (!admin || !admin.is_active) {
        return res.status(401).json({
          code: 401,
          message: '账户已被禁用',
          timestamp: Date.now()
        });
      }

      // 检查角色权限
      const hasPermission = requiredRoles.some(role => admin.hasPermission(role));
      if (!hasPermission) {
        return res.status(403).json({
          code: 403,
          message: '权限不足',
          timestamp: Date.now()
        });
      }

      req.adminInfo = admin;
      next();
    } catch (error) {
      console.error('权限检查失败:', error);
      return res.status(500).json({
        code: 500,
        message: '权限检查失败',
        timestamp: Date.now()
      });
    }
  };
}

/**
 * 可选认证中间件（不强制要求认证）
 */
function optionalAuth(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (token) {
    try {
      const decoded = verifyToken(token);
      req.admin = decoded;
    } catch (error) {
      // 忽略token验证失败，继续执行
    }
  }

  next();
}

/**
 * 检查管理员状态中间件
 */
async function checkAdminStatus(req, res, next) {
  try {
    if (!req.admin) {
      return next();
    }

    const admin = await Admin.findById(req.admin.id);
    if (!admin) {
      return res.status(401).json({
        code: 401,
        message: '管理员账户不存在',
        timestamp: Date.now()
      });
    }

    if (!admin.is_active) {
      return res.status(401).json({
        code: 401,
        message: '管理员账户已被禁用',
        timestamp: Date.now()
      });
    }

    req.adminInfo = admin;
    next();
  } catch (error) {
    console.error('检查管理员状态失败:', error);
    return res.status(500).json({
      code: 500,
      message: '检查管理员状态失败',
      timestamp: Date.now()
    });
  }
}

/**
 * 自己或超级管理员才能操作的中间件
 */
function requireSelfOrSuperAdmin(req, res, next) {
  const targetAdminId = parseInt(req.params.id || req.body.id);
  const currentAdminId = req.admin.id;
  const currentAdminRole = req.adminInfo ? req.adminInfo.role : req.admin.role;

  if (currentAdminId === targetAdminId || currentAdminRole === 'super_admin') {
    next();
  } else {
    return res.status(403).json({
      code: 403,
      message: '只能修改自己的信息或需要超级管理员权限',
      timestamp: Date.now()
    });
  }
}

/**
 * Token刷新中间件
 */
function refreshToken(req, res, next) {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '未提供认证令牌',
        timestamp: Date.now()
      });
    }

    // 验证token（即使过期也要解析）
    let decoded;
    try {
      decoded = jwt.verify(token, JWT_SECRET);
    } catch (error) {
      if (error.name === 'TokenExpiredError') {
        // Token过期，尝试解析载荷
        decoded = jwt.decode(token);
        if (!decoded) {
          return res.status(401).json({
            code: 401,
            message: '无效的认证令牌',
            timestamp: Date.now()
          });
        }
      } else {
        return res.status(401).json({
          code: 401,
          message: '无效的认证令牌',
          timestamp: Date.now()
        });
      }
    }

    // 生成新token
    const newToken = generateToken({
      id: decoded.id,
      username: decoded.username,
      role: decoded.role
    });

    res.json({
      code: 200,
      message: 'Token刷新成功',
      data: {
        token: newToken,
        expires_in: parseInt(JWT_EXPIRES_IN)
      },
      timestamp: Date.now()
    });
  } catch (error) {
    console.error('Token刷新失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'Token刷新失败',
      timestamp: Date.now()
    });
  }
}

module.exports = {
  generateToken,
  verifyToken,
  authenticateToken,
  requireRole,
  optionalAuth,
  checkAdminStatus,
  requireSelfOrSuperAdmin,
  refreshToken
}; 